<template>
  <div class="container">
    <div class="header">
      <span class="project-title-font">{{ project.projectName }}</span>
      <div>
        <a-button type="primary" @click="projectManagementModal = true" v-if="permission">
          <SettingOutlined /> 管理
        </a-button>
        <a-divider type="vertical"></a-divider>
        <a-button @click="remindModal = true" v-if="permission"> <BulbOutlined /> 提醒 </a-button>
      </div>
    </div>
    <a-spin :spinning="projectLoading">
      <div class="body">
        <div class="left-body">
          <!-- 项目基本信息 -->

          <div class="left-firstCard">
            <div class="left-firstCard-main">
              <div style="width: 25%">
                <span class="overview-info-font">项目负责人</span>
                <div class="project-leader-list">
                  <div v-if="projectType == 1" v-for="user in project.userList" :key="user.userId">
                    <OverviewCard v-if="user.type === 0" :message="user.userName" tips="负责人" />
                  </div>
                  <div else v-for="user in project.managerList" :key="user.userId">
                    <OverviewCard :message="user.userName" tips="负责人" />
                  </div>
                </div>
              </div>
              <a-divider type="vertical" style="margin: 0px 10px; height: 100%"></a-divider>
              <div style="width: 65%">
                <span class="overview-info-font">项目时间</span>
                <div class="project-time-box">
                  <OverviewCard
                    type="Date"
                    icon="CalendarOutlined"
                    :message="project.startTime"
                    tips="开始时间"
                  />
                  <OverviewCard
                    type="Date"
                    icon="CarryOutOutlined"
                    :message="project.endTime"
                    tips="结束时间"
                  />
                </div>
                <a-divider style="margin: 10px 0"></a-divider>

                <span class="overview-info-font">项目描述</span>

                <div style="margin-top: 10px">
                  {{ project.projectDescription }}
                </div>
              </div>
            </div>

            <div>
              <span class="project-created-info">
                创建者: {{ project.creatorName }} · 创建时间:{{
                  dayjs(project.createTime).format('YYYY-MM-DD HH:mm:ss')
                }}
              </span>
            </div>
          </div>

          <!-- 项目成员 -->
          <a-collapse
            class="left-card"
            :bordered="false"
            :forceRender="true"
            v-model:activeKey="activeKey"
          >
            <a-collapse-panel header="项目成员" key="1">
              <div
                style="
                  display: flex;
                  justify-content: space-between;
                  align-items: center;
                  margin: 0 0 10px 0;
                "
              >
                <a-input-search
                  v-model:value="searchMember"
                  placeholder="根据名称搜索成员"
                  allow-clear
                  style="width: 350px"
                  @search="findMember"
                  :pressEnter="findMember"
                />
                <span>
                  {{ memberData.length }}
                  <span style="color: #9999">位成员</span>
                </span>
                <a-button
                  size="small"
                  @click="addMumberModal = true"
                  v-if="permission && projectType == 1"
                >
                  <template #icon>
                    <PlusOutlined />
                  </template>
                </a-button>
              </div>
              <a-table
                :columns="memberColumns"
                :data-source="memberData"
                :pagination="false"
                :scroll="{ y: 190 }"
              >
                <template #bodyCell="{ column, text, record }">
                  <template v-if="column.dataIndex === 'name'">
                    <a-avatar size="large" style="background-color: #7265e6" :gap="2">
                      {{ text }}
                    </a-avatar>
                    {{ text }}
                  </template>
                  <template v-else-if="column.dataIndex === 'type'">
                    <span v-if="record.type === 0">负责人</span>
                    <span v-else-if="record.type === 1">普通成员</span>
                  </template>
                  <template v-else-if="column.dataIndex === 'groupName'">
                    <span v-if="record.groupId === 0">默认组</span>
                  </template>
                </template>
              </a-table>
            </a-collapse-panel>
          </a-collapse>
        </div>

        <div class="right-card">
          <!-- 项目状态 -->

          <div>
            <span class="overview-info-font">状态信息：</span>
            <span v-if="project.projectStatus === 0"
              ><a-tag color="error" style="margin-left: 10px">已删除</a-tag></span
            >
            <span v-else-if="project.projectStatus === 1"
              ><a-tag color="default" style="margin-left: 10px">未启动</a-tag></span
            >
            <span v-else-if="project.projectStatus === 2"
              ><a-tag color="processing" style="margin-left: 10px">进行中</a-tag></span
            >
            <span v-else-if="project.projectStatus === 3"
              ><a-tag color="warning" style="margin-left: 10px"> 已暂停</a-tag></span
            >
            <span v-else-if="project.projectStatus === 4"
              ><a-tag color="success" style="margin-left: 10px">已结束</a-tag></span
            >
          </div>

          <a-divider style="margin: 10px 0"></a-divider>
          <a-progress :percent="defaultPercent" />

          <!-- 项目课程 -->

          <div v-if="store.getters.projectType === 2">
            <div style="display: flex; justify-content: space-between; align-items: center">
              <span class="overview-info-font">关联课程</span>
              <a-button size="small" v-if="permission" @click="addCourseModal = true">
                <template #icon>
                  <PlusOutlined />
                </template>
              </a-button>
            </div>
            <a-divider style="margin: 10px 0"></a-divider>
            <a-list item-layout="horizontal" :data-source="courseData" class="courseList">
              <template #renderItem="{ item }">
                <a-list-item>
                  <a> {{ item.courseName }}</a>
                </a-list-item>
              </template>
            </a-list>
            <a-divider style="margin: 10px 0"></a-divider>
          </div>

          <!-- 任务统计 -->
          <div style="margin: 10px 0">
            <span class="overview-info-font">任务统计</span>
          </div>
          <div class="task-statistics">
            <a-spin :spinning="taskLoading">
              <a-row>
                <a-col :span="8">
                  <a-statistic title="分配总数">
                    <template #formatter>
                      <span class="task-value" @click="openTaskWin(0)">{{ task.total }}</span>
                    </template>
                  </a-statistic>
                </a-col>
                <a-col :span="8">
                  <a-statistic title="已完成">
                    <template #formatter>
                      <span class="task-value" @click="openTaskWin(1)">{{ task.completed }}</span>
                    </template>
                  </a-statistic>
                </a-col>
                <a-col :span="8">
                  <a-statistic title="进行中">
                    <template #formatter>
                      <span class="task-value" @click="openTaskWin(2)">{{ task.inProgress }}</span>
                    </template>
                  </a-statistic>
                </a-col>
              </a-row>
              <a-row>
                <a-col :span="8">
                  <a-statistic title="待领取">
                    <template #formatter>
                      <span class="task-value" @click="openTaskWin(3)">{{ task.notStarted }}</span>
                    </template>
                  </a-statistic>
                </a-col>
                <a-col :span="8">
                  <a-statistic title="延期任务">
                    <template #formatter>
                      <span class="task-value" @click="openTaskWin(4)">{{ task.extension }}</span>
                    </template>
                  </a-statistic>
                </a-col>
                <a-col :span="8">
                  <a-statistic title="待验收">
                    <template #formatter>
                      <span class="task-value" @click="openTaskWin(5)">{{ task.notReviewed }}</span>
                    </template>
                  </a-statistic>
                </a-col>
              </a-row>
              <a-row>
                <a-col :span="8">
                  <a-statistic>
                    <template #title>
                      <span style="margin-left: 11px">完成率</span>
                      <a-tooltip placement="right">
                        <template #title>
                          <span>已完成任务/任务总数</span>
                        </template>
                        <question-circle-two-tone style="margin-left: 5px" />
                      </a-tooltip>
                    </template>
                    <template #formatter>
                      <span style="color: #73d897">
                        {{
                          task.total === 0
                            ? 0 + '%'
                            : ((task.completed / task.total) * 100).toFixed(1) + '%'
                        }}</span
                      >
                    </template>
                  </a-statistic>
                </a-col>
                <a-col :span="8">
                  <a-statistic>
                    <template #title>
                      <span style="margin-left: 11px">延期率</span>
                      <a-tooltip placement="right">
                        <template #title>
                          <span>延期未完成/任务总数</span>
                        </template>
                        <question-circle-two-tone style="margin-left: 5px" />
                      </a-tooltip>
                    </template>
                    <template #formatter>
                      <span style="color: #ff7575">
                        {{
                          task.total === 0
                            ? 0 + '%'
                            : ((task.extension / task.total) * 100).toFixed(1) + '%'
                        }}
                      </span>
                    </template>
                  </a-statistic>
                </a-col>
              </a-row>
            </a-spin>
          </div>
        </div>
      </div>
    </a-spin>
  </div>
  <!-- 任务概述窗口 -->
  <TaskStatisticsModal v-model:model-visible="taskStatisticsModel" :task-table="taskTable" />
  <!-- 项目管理窗口 -->
  <ProjectManagementModal
    v-model:model-visible="projectManagementModal"
    :project="project"
    @confirm="findProject"
  />
  <!-- 提醒窗口 -->
  <RemindModal v-model:model-visible="remindModal" />
  <!-- 添加人员窗口 -->
  <AddMumberModal
    v-model:modelVisible="addMumberModal"
    :memberList="memberData"
    @confirm="findProject"
  />
  <!-- 添加课程窗口 -->
  <AddCourseModal
    v-model:modelVisible="addCourseModal"
    :course-list="project.courseList"
    @confirm="findProject"
  />
</template>
<script lang="ts" setup>
import TaskStatisticsModal from './taskStatisticsModal.vue';
import ProjectManagementModal from './projectManagementModal.vue';
import AddMumberModal from './addMumberModal.vue';
import AddCourseModal from './addCourseModal.vue';
import OverviewCard from '@/components/OverviewCard/index.vue';
import RemindModal from './remindModal.vue';
import ProjecrDao from '@/daos/project_dao';
import TaskDao from '@/daos/task_dao';
import dayjs from 'dayjs';
import { useStore } from 'vuex';
const store = useStore();
const projectDao = new ProjecrDao();
const taskDao = new TaskDao();

onMounted(() => {
  findProject();
  findTaskNumber();
});

//权限开关
const permission = ref<boolean>(false);

//项目ID
const projectId = store.getters.projectId;
//项目类型
const projectType = store.getters.projectType;
//项目成员列表
const memberData = ref([]);
//课程列表
const courseData = ref([]);

//窗口开关
const taskStatisticsModel = ref(false);
const projectManagementModal = ref(false);
const remindModal = ref(false);
const addMumberModal = ref(false);
const addCourseModal = ref(false);
const taskTable = ref<number>(0);
//进度条
const defaultPercent = ref<number>();
//查询项目成员输入框
const searchMember = ref<string>('');
//项目基本信息projectType
let project = ref({
  projectId: undefined,
  projectName: '',
  projectDescription: '',
  userList: [],
  managerList: [],
  teacherList: [],
  studentList: [],
  startTime: undefined,
  createTime: undefined,
  endTime: undefined,
  finishTime: undefined,
  creatorId: undefined,
  creatorName: '',
  projectStatus: undefined,
  courseList: []
});
//加载开关
const projectLoading = ref(true);
const taskLoading = ref(true);
//项目折叠面板开关
const activeKey = ref([1, 2]);
//任务分配信息
const task = ref({
  completed: 0,
  extension: 0,
  inProgress: 0,
  notReviewed: 0,
  notStarted: 0,
  total: 0
});
//查询项目信息（包括基本信息+人员信息+课程信息）
const findProject = () => {
  projectLoading.value = true;
  projectDao
    .findProjectByProjectId(projectId, projectType)
    .then((result) => {
      if (projectType == 1) {
        project.value = result.data.data;
        memberData.value = project.value.userList;
        setPermission(project.value.userList.find((user) => user.userId === store.getters.userId));
        projectLoading.value = false;
      } else if (projectType == 2) {
        project.value = result.data.data;
        memberData.value = project.value.studentList;
        courseData.value = project.value.courseList;
        store.commit('project/SET_COURSES', courseData.value);
        setPermission(
          project.value.managerList.find((user) => user.userId === store.getters.userId)
        );
        projectLoading.value = false;
      }
    })
    .catch((error) => {
      console.error('findProjectByProjectId error', error);
      projectLoading.value = false;
    });
};
//查询项目任务的分配数量
const findTaskNumber = async () => {
  taskLoading.value = true;
  const result = await taskDao.findTaskAssignmentNumber(projectId, 1);
  task.value = result.data.data;
  taskLoading.value = false;
};

//检查是否开发部分按钮权限
const setPermission = (user) => {
  if (projectType == 1) {
    if (user?.type === 0) {
      permission.value = true;
      store.commit('user/SET_USERTYPE', user?.type);
    } else {
      permission.value = false;
      store.commit('user/SET_USERTYPE', user?.type);
    }
  } else if (projectType == 2) {
    if (user) {
      permission.value = true;
      store.commit('user/SET_USERTYPE', 0);
      store.commit('user/SET_PERMISSION', true);
    } else {
      store.commit('user/SET_USERTYPE', 1);
      store.commit('user/SET_PERMISSION', false);
    }
  }
};
//查询人员
const findMember = async () => {
  const result = await projectDao.findProjectMemberByProjectId(
    projectId,
    searchMember.value,
    projectType
  );
  memberData.value = result.data.data;
};

const memberColumns = [
  {
    title: '成员',
    dataIndex: 'userName',
    customHeaderCell: () => ({ style: { fontWeight: '400' } })
  },
  ...(projectType === 2
    ? [
        {
          title: '小组名',
          dataIndex: 'teamName',
          customHeaderCell: () => ({ style: { fontWeight: '400' } })
        }
      ]
    : []),
  ...(projectType === 1
    ? [
        {
          title: '身份',
          dataIndex: 'type',
          customHeaderCell: () => ({ style: { fontWeight: '400' } })
        }
      ]
    : [])
];

const openTaskWin = (index: number) => {
  taskStatisticsModel.value = true;
  taskTable.value = index;
};
</script>
<style scoped lang="scss">
.container {
  background: #fafafa;
  display: flex;
  flex-direction: column;
  height: 100%;
  .header {
    height: 60px;
    min-height: 50px;
    min-width: 1080px;
    padding: 0 10px 0 30px;

    display: flex;
    justify-content: space-between;
    background: #fff;
    align-items: center;
    border: 1px;
    border-radius: 8px;
    box-shadow: 2px 2px 8px rgba(0, 0, 0, 0.1);

    position: sticky; /* 使用 sticky 定位 */
    top: 0; /* 固定在顶部 */
    z-index: 1000; /* 确保 header 在最上层 */
    .project-title {
      font-size: 24px;
      margin-bottom: 20px;
    }

    .project-title-font {
      font-size: 20px;
      font-weight: 600;
      color: #333;
    }
  }

  .body {
    display: flex;
    background: #fafafa;
    padding: 15px;
    .left-body {
      height: 100%;
      width: 60%;
      min-width: 640px;
      display: flex;
      flex-direction: column;

      .left-firstCard {
        padding: 5px 0px;
        height: 40%;
        background-color: #fff;
        margin-bottom: 8px;
        border: 1px solid #eee;
        padding: 15px 15px 15px 24px;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        .left-firstCard-main {
          height: 85%;
          display: flex;
          justify-content: space-around;
          margin-bottom: 15px;
        }
      }

      .left-card {
        max-height: 600px;
        padding: 5px 0px;
        background-color: #fff;
        margin-top: 8px;
        border: 1px solid #eee;
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      }
    }

    .right-card {
      width: 39%;
      height: 100%;
      min-width: 400px;
      min-height: 580px;
      padding: 15px 15px 15px 24px;
      margin-left: 8px;
      background-color: #fff;
      border: 1px solid #eee;
      overflow-y: auto;
      border-radius: 8px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      .courseList {
        max-height: 180px;
        min-width: 300px;
        overflow-y: auto;
      }

      .task-statistics {
        width: 100%;
        margin: auto auto;
        text-align: center;
      }
    }
  }
}

.project-leader-list {
  display: flex;
  flex-direction: column;
  height: 80%;
  overflow-y: auto;
  margin-top: 10px;
}

.project-time-box {
  display: flex;
  justify-content: space-around;
  margin-top: 10px;
}

.project-created-info {
  font-size: 14px;
  color: #6666;
}

.overview-info-font {
  font-size: 14px;
  color: #6666;
}

.task-value:hover {
  cursor: pointer;
  color: #1677ff !important;
}
</style>
